<?php

namespace App\Http\Controllers\Index;

use App\Http\Controllers\Controller;
use App\Serves\CartServe;
use App\Utils\Show;
use Illuminate\Http\Request;
use App\Http\Controllers\Index\UserAuth;
use Illuminate\Support\Facades\Redis;
class Cart extends UserAuth
{
    //
    public function __construct(Request $request)
    {
        parent::__construct($request);

    }

    public function index(Request $request){
        $params = $request->all();
//        $user_id = $params['user_id'];
//        $user_id = $this->>userId;
        $user_id = 8;
        $all_Carts = CartServe::allCarts($user_id, $ids=[]);
        return view('index.cart')->with([
                'all_Carts'=>$all_Carts,
        ]);;
    }

    /**
     * 删除单个购物车
     */
    public function delCarts(Request $request){
        if(!$request->isMethod('POST')) return Show::error();

        $params = $request->all();

        if(!$params['id'] || !isset($params['id'])) return Show::error();
        $res = CartServe::del($params['id'] , $this->userId);
        if($res) return Show::success();
        return Show::error();
    }

    /**
     * 更新购物车
     */
    public function updateCarts(Request $request){
        if(!$request->isMethod('POST')) return Show::error();

        $params = $request->all();

        if(!$params['id'] || !isset($params['id']) || !$params['num'] || !isset($params['num'])) return Show::error();

        $res = CartServe::update($params['id'] ,$params['num'],  $this->userId);
        if($res===1 || $res ===0) return Show::success();
        return Show::error();
    }



    public function addCart(Request $request){
        $params = $request->all();

        $result = CartServe::getGoodAndGoodSku($params['sku_id'], $params['num']);
        if(!$result) return showMsg(0,'err', []);
        $data = [
            'name'=>$result->goods->name,
            'num'=>intval($params['num']),
            'image'=>$result->goods->main_image,
            'goods_id'=>$result->goods->id,
            'create_time'=>time(),
        ];
        //数量处理 先判断这个skuid书是否存在

//        $res = Redis::hset(config('redis.pre_user_cart').$this->userId, $params['sku_id'], json_encode($data));
        $has = Redis::hget(config('redis.pre_user_cart').$this->userId, $params['sku_id']);
        if($has){
            $has_res = json_decode($has,true);
            $data['num'] += $has_res['num'];
        }
//        rediskey 是可以封装一个基础类库  config('redis.pre_user_cart').$this->userId
        $res = Redis::hset(config('redis.pre_user_cart').$this->userId, $params['sku_id'], json_encode($data));
//        var_dump($res);
        if($res===1 || $res ===0) return Show::success();


    }
}
